package org.hefan.hrm.service.impl;

import org.hefan.hrm.exception.ValidUtil;
import org.hefan.hrm.service.IImageVerifyCodeService;
import org.hefan.hrm.util.AjaxResult;
import org.hefan.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ImageVerifyCodeServiceImpl implements IImageVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取图片验证码并返回前端
     * 保存验证码到redis中
     * @param imageCodeKey
     * @return
     */
    @Override
    public AjaxResult getCodeByKey(String imageCodeKey) {
        // 非空校验
        ValidUtil.assertNotNull(imageCodeKey, "非法操作，请重试！");
        // 产生字符串验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 字节输出流
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            VerifyCodeUtils.outputImage(140, 40, data, code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对图片进行base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String imgBase64Data = encoder.encode(data.toByteArray());
        // 把字符串验证码放进redis
        long expireTime = 3;
        redisTemplate.opsForValue().set(imageCodeKey, code, expireTime, TimeUnit.MINUTES);
        // 返回base64编码数据
        return AjaxResult.me().setResultObj(imgBase64Data);
    }

    /**
     * 将前端输入的验证码和redis中的验证码进行比较
     * @param params
     * @return
     */
    @Override
    public AjaxResult verifyCode(Map<String, String> params) {
        // 获取key和code
        String imageCodeKey = params.get("imageCodeKey");
        String imageCode = params.get("imageCode");
        // 通过key从redis获取redisCode
        String redisCode = (String) redisTemplate.opsForValue().get(imageCodeKey);
        // 比较前端输入的code和redis中的code是否相等
        return imageCode.equalsIgnoreCase(redisCode) ? AjaxResult.me()
                : AjaxResult.me().setSuccess(false).setMessage("图片验证码不正确");
    }
}
